package com.miyuan.wm.aop;

import java.lang.reflect.Method;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.miyuan.wm.data.UserInfo;
import com.miyuan.wm.service.SystemLogService;

import lombok.extern.slf4j.Slf4j;

@Aspect
@Component
@Slf4j
public class UserOperationLogAspect {
	
	@Autowired
	private SystemLogService systemLogService;

	@Pointcut("@annotation(com.miyuan.wm.aop.UserOperation)")
	public void addAdvice() {
	}
	
	@AfterReturning(returning = "returnValue", pointcut = "addAdvice()")
    public void afterPointcut(JoinPoint joinPoint, Object returnValue) {
        MethodSignature methodSignature =  (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        UserOperation userOperation = method.getAnnotation(UserOperation.class);
        if (userOperation != null) {
			// 获取 annotation 的值
			String userOperationValue = userOperation.value();

			// 获取调用的方法名
			String methodName = joinPoint.getSignature().getName();
			
			// 获取除 import* export* 外的方法的返回值
			String invokedResult = "-";
			if (!methodName.matches("^import\\w*") && !methodName.matches("^export\\w*")) {
				if (returnValue instanceof Boolean) {
					boolean result = (boolean) returnValue;
					invokedResult = result ? "成功" : "失败";
				}
			}
			// 获取用户信息
			Subject currentSubject = SecurityUtils.getSubject();
			Session session = currentSubject.getSession();
			UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
			Integer userID = userInfo.getUserID();
			String userName = userInfo.getUserName();
			// 插入记录
			try {
				systemLogService.insertUserOperationRecord(userID, userName, userOperationValue, invokedResult);
			} catch (Exception e) {
				log.error("异常", e);
			}
		}
    }

}
